package com.sasis.webapp.action;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.sasis.model.OperLog;
import com.sasis.model.UserInfo;
import com.sasis.service.OperLogService;
import com.sasis.service.UserInfoService;
import com.sasis.util.DateUtil;
import com.sasis.util.PageList;
import com.sasis.util.PageRequest;
import com.sasis.util.StringUtil;

public class OperLogAction extends BaseAction {

	private static final String SQL_DEFAULT = "findAllOperLog";

	private static final int PAGE_SIZE = 10;

	private static final int USER_IS_USEABLE = -1;

	public ActionForward view(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		OperLogService mgr = (OperLogService) getBean("operLogManager");
		String id = request.getParameter("id");
		if (id != null && !id.equals("")) {
			OperLog log = mgr.loadOperLog(new Integer(id));
			log.setLogTime(DateUtil.toDateString("yyyy-MM-dd hh:mm", String
					.valueOf(log.getLogTime())));
			request.setAttribute("log", log);
		}
		return mapping.findForward("view");
	}

	public ActionForward unspecified(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		System.out.println(request.getParameter("operator") + "---"
				+ request.getParameter("opTime"));
		Map map = new HashMap();
		String operator = request.getParameter("operator");
		Integer op = new Integer(-1);
		if(operator!=null&&!operator.equals("")){
			op = new Integer(operator);
		}
		map.put("operator", op);
		String time = request.getParameter("opTime");
		long t = 0;
		if (time != null && !time.equals("")) {
			t = DateUtil.DateString2Long("yyyy-MM-dd hh:mm", time);
		}
		map.put("opTime", new Long(t));
		OperLogService mgr = (OperLogService) getBean("operLogManager");
		int pageIndex = !StringUtil.isEmpty(request.getParameter("pageIndex")) ? Integer
				.parseInt(request.getParameter("pageIndex"))
				: 0;
		PageList list = mgr.queryForPageList(SQL_DEFAULT, map, new PageRequest(
				pageIndex, PAGE_SIZE));
		request.setAttribute("logList", list);
		setUserToReuqest(request);
		return mapping.findForward("list");
	}

	private void setUserToReuqest(HttpServletRequest request) {
		UserInfoService userInfoService = (UserInfoService) getBean("userInfoService");
		UserInfo u = new UserInfo();
		u.setIsUsable(USER_IS_USEABLE);
		List users = userInfoService.getAllUsers(u);
		request.setAttribute("users", users);
	}

}
